<template>
    <div>
<!--        导航-->
        <bread-nav>
            <span slot="nav1">商品管理</span>
            <span slot="nav2">添加商品</span>
        </bread-nav>
<!--        卡片视图-->
        <el-card>
            <el-alert
                    title="请添加商品"
                    type="info"
                    center
                    :closable="false"
                    show-icon>
            </el-alert>
<!--            进度条-->
            <el-steps :space="400" :active="activeIndex - 0" finish-status="success"
            align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
<!--           tab面板-->
            <div class="tab_panel">
                <el-form label-position="top" :model="goodForm" :rules="goodRule" ref="goodRef">
                <el-tabs tab-position="left"  v-model="activeIndex" @tab-click="changePanel"
                :before-leave="tabLeaveClick">
                        <el-tab-pane label="基本信息" name="0">
                            <el-form-item label="商品名称" prop="goods_name">
                                <el-input v-model="goodForm.goods_name"></el-input>
                            </el-form-item>
                            <el-form-item label="商品价格" prop="goods_price">
                                <el-input v-model="goodForm.goods_price"></el-input>
                            </el-form-item>
                            <el-form-item label="商品数量" prop="goods_number">
                                <el-input v-model="goodForm.goods_number"></el-input>
                            </el-form-item>
                            <el-form-item label="商品重量" prop="goods_weight">
                                <el-input v-model="goodForm.goods_weight"></el-input>
                            </el-form-item>
                            <el-form-item label="商品分类">
<!--                                级联选择器-->
                                <el-cascader
                                        v-model="goodForm.goods_cat"
                                        :options="goodsCatList"
                                        :props="cascaderProps"
                                        :clearable="true"
                                        @change="handleChange"></el-cascader>
                            </el-form-item>
                        </el-tab-pane>
                        <el-tab-pane label="商品参数" name="1">
                            <el-form-item v-for="(item,index) in manyList" :key="index"
                                          :label="item.attr_name">
                                <el-checkbox v-model="item.attr_vals" :label="items"
                                             v-for="(items,index1) in item.attr_vals"
                                             border :key="index1">
                                </el-checkbox>
                            </el-form-item>
                        </el-tab-pane>
                        <el-tab-pane label="商品属性" name="2">
                            <el-form-item v-for="(item,index) in onlyList" :key="index"
                                          :label="item.attr_name">
                                <el-checkbox v-model="item.attr_vals" :label="items"
                                             v-for="(items,index1) in item.attr_vals"
                                             border :key="index1">
                                </el-checkbox>
                            </el-form-item>
                        </el-tab-pane>
                        <el-tab-pane label="商品图片" name="3">
                            <el-upload
                                    action="http://timemeetyou.com:8889/api/private/v1/upload"
                                    :on-preview="handlePreview"
                                    :on-remove="handleRemove"
                                    :on-success="handleSuccess"
                                    :headers="imgUploadHeader"
                                    list-type="picture">
                                <el-button size="small" type="primary">点击上传</el-button>
                                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                            </el-upload>
                        </el-tab-pane>
                        <el-tab-pane label="商品内容" name="4">
                            <quill-editor v-model="goodForm.goods_introduce"></quill-editor>
                            <el-button type="primary" @click="addGood" class="add_good_btn">添加商品</el-button>
                        </el-tab-pane>
                </el-tabs>
                </el-form>
            </div>
        </el-card>
<!--        图片预览-->
        <el-dialog
                :visible.sync="previewVisible" width="50%">
            <img :src="imgUrl" width="100%"/>
        </el-dialog>
    </div>
</template>

<script>
    import BreadNav from "../../components/content/BreadNav";
    import {getShopCate,addGoodInfo} from "../../network/goods";
    import {getGoodsPam} from "../../network/goodsParams";
    import _  from 'lodash';

    export default {
        name: "AddGood",
        data(){
            return {
                activeIndex:'0',
                goodForm:{
                    goods_name:'',
                    goods_cat:[],
                    goods_price:'',
                    goods_number:'',
                    goods_weight:'',
                    goods_introduce:'',
                    pics:[],
                    attrs:[]
                },
                //表单校验规则
                goodRule:{
                    goods_name:[{required:true,message:'请输入商品名称',trigger:'blur'}],
                    goods_price:[{required:true,message:'请输入商品价格',trigger:'blur'}],
                    goods_number:[{required:true,message:'请输入商品数量',trigger:'blur'}],
                    goods_weight:[{required:true,message:'请输入商品重量',trigger:'blur'}],
                },
                cascaderProps:{
                    label:"cat_name",
                    value:"cat_id",
                    expandTrigger: 'hover',
                    checkStrictly:true
                },
                goodsCatList:[],//商品分类列表
                catId:'',
                manyList:[],//动态参数列表
                onlyList:[],//动态参数列表
                imgUploadHeader:{
                    Authorization:sessionStorage.getItem('token')
                },//设置上传图片网络请求头，携带token
                previewVisible:false,
                imgUrl:''
            }
        },
        components:{
            BreadNav
        },
        methods:{
            //监听级联选择器事件
            handleChange(){
                if (this.goodForm.goods_cat.length !== 3 ){
                    this.$message.warning('请选择三级分类！');
                    this.goodForm.goods_cat = []
                }else{
                    this.catId = this.goodForm.goods_cat[this.goodForm.goods_cat.length - 1]
                }
            },
            //获取分类数据
            getShopCateM(){
                getShopCate({tyep:3}).then(res => {
                        // console.log(res);
                        this.goodsCatList = res.data.data
                    }
                )
            },
            //监听面板切换事件
            changePanel(){
                if(this.activeIndex === '1'){
                    getGoodsPam(this.catId,'many').then(res => {
                        this.manyList = res.data.data;
                        this.manyList.forEach(item => {
                            item.attr_vals = item.attr_vals.split(',')
                        });
                    })
                }else if(this.activeIndex === '2'){
                    getGoodsPam(this.catId,'only').then(res => {
                        this.onlyList = res.data.data;
                        this.onlyList.forEach(item => {
                            item.attr_vals = item.attr_vals.split(',')
                        });
                        // console.log(res)
                    })
                }
            },
            //阻止面板切换
            tabLeaveClick(activeName,oldActiveName){
                if(activeName !== '0' && this.goodForm.goods_cat.length !== 3){
                    this.$message.warning('请选择三级分类！');
                    return false
                }else if (oldActiveName === '0' && this.goodForm.goods_cat.length === 3){
                    this.$refs.goodRef.validate(valid => {
                            if(valid !== true){
                                this.$message.warning('请输入完整的信息！');
                            }
                    });
                }
            },
            //移除图片事件
            handleRemove(file){
                const filePath = file.response.data.tmp_path;
                const index = this.goodForm.pics.findIndex(item => {
                    item.tmp_path === filePath
                });
                this.goodForm.pics.splice(index,1);
            },
            //图片预览事件
            handlePreview(file){
                this.imgUrl = file.response.data.url;
                this.previewVisible = true
            },
            //图片上传成功事件
            handleSuccess(response){
                const path = {
                    tmp_path:response.data.tmp_path
                };
                this.goodForm.pics.push(path);
                // console.log(this.goodForm)
            },
            //添加商品，发送网络请求
            addGood() {
                this.$refs.goodRef.validate(valid => {
                    if (valid !== true) {
                        this.$message.warning('请输入完整的信息！');
                    } else {
                        //深拷贝
                        const form = _.cloneDeep(this.goodForm);
                        form.goods_cat = form.goods_cat.join(',');
                        //处理动态参数和静态属性
                        this.manyList.forEach(item => {
                            const attr_info = {attr_id:item.attr_id,attr_vals:item.attr_vals.join(',')};
                            this.goodForm.attrs.push(attr_info)
                        });
                        this.onlyList.forEach(item => {
                            const attr_info = {attr_id:item.attr_id,attr_vals:item.attr_vals.join(',')};
                            this.goodForm.attrs.push(attr_info)
                        });
                        form.attrs = this.goodForm.attrs;
                       addGoodInfo(form).then(res => {
                           if(res.data.meta.status !== 201){
                               this.$message.error(res.data.meta.msg)
                           }else{
                               this.$message.success(res.data.meta.msg);
                               this.$router.push('/goods')
                           }
                       })
                    }
                })
            }
        },
        mounted() {
            this.getShopCateM()
        }
    }
</script>

<style scoped lang="less">
    .el-steps{
        margin-top: 1rem;
    }
    .tab_panel{
        margin-top: 1rem;
    }
    .add_good_btn{
        margin-top: 1rem;
    }

</style>